package org.eraser.login;

import org.eraser.common.ResultEntity;
import org.eraser.Oauth2CoreConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;

@Controller
public class AuthenticationController {

    private static final String loginPageUri = Oauth2CoreConfig.loginPageUri;
    private static final String loginSuccessUri = Oauth2CoreConfig.loginSuccessUri;
    private static final String loginFailureUri = Oauth2CoreConfig.loginFailureUri;

    @Autowired
    private InMemoryClientRegistrationRepository clientRegistrationRepository;

    @GetMapping(loginPageUri)
    public ModelAndView loginPage() {
        ArrayList<String> registrationIds = new ArrayList<String>();
        for (ClientRegistration next : clientRegistrationRepository) {
            String registrationId = next.getRegistrationId();
            registrationIds.add(registrationId);
        }

        ModelAndView modelAndView = new ModelAndView("login");
        modelAndView.addObject("registrationIds", registrationIds);
        return modelAndView;
    }

    @GetMapping(loginSuccessUri)
    @ResponseBody
    public ResultEntity<OAuth2AuthenticationToken> loginSuccess() {
        OAuth2AuthenticationToken authentication = (OAuth2AuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        return ResultEntity.result(authentication, "LS200", "成功");
    }

    @GetMapping(loginFailureUri)
    @ResponseBody
    public ResultEntity<String> loginFailureUri() {
        return ResultEntity.result("认证失败", "LF500", "失败");
    }

}
